// pages/cart/index.js
import {getSetting, openSetting, chooseAddress, showToast} from '../../utils/asyncWx.js';
import regeneratorRuntime from '../../lib/runtime/runtime.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    allChecked: false,
    totalPrice: 0,
    totalNumber: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    const address = wx.getStorageSync("address")
    const cart = wx.getStorageSync("cart") || []
    // 计算全选
    // 空数组调用 every 返回值为 true 
    const allChecked = cart.length?cart.every(v => v.checked):false
    let totalPrice = 0
    let totalNumber = 0
    // 选中了才计算。。。。
    cart.forEach(v => {
    if (v.checked) {
      totalPrice += v.goods_price * v.num
      totalNumber += v.num
    }
    })
    this.setData({
      address,
      cart,
      allChecked,
      totalPrice,
      totalNumber
    })
  },

  async handleChooseAddress () {
    // 1. 获取权限状态
    // wx.getSetting({
    //   success: (result) => {
    //     // 只要发现一些属性名很怪异 都要使用[]形式获取属性值
    //     const scopeAddress = result.authSetting["scope.address"]
    //     // 先一下用户的权限状态，如果用户以前没有点击过获取地理位置，或在获取地理位置时点击了确定
    //     if (scopeAddress === true || scopeAddress===undefined) {
    //       wx.chooseAddress({
    //         success: (result1) => {
    //           console.log(result1)
    //         }
    //       });
    //     } else {
    //       // 用户以前拒绝过权限 先诱导用户打开授权页面
    //       wx.openSetting({
    //         success: (result2) => {
    //           // 可以调用收货地址代码
    //           wx.chooseAddress({
    //             success: (result3) => {
    //               console.log(result3)
    //             }
    //           });
                
    //         }
    //       });
            
    //     }
    //   }
      
    // });

    try {
      // 1，获取权限状态
    const res1 = await getSetting();
    const scopeAddress = res1.authSetting["scope.address"]
    // 2 判断状态权限
    if (scopeAddress === true || scopeAddress===undefined) {
      // 3 调用获取收货地址的 api 
      const address = await chooseAddress();
      wx.setStorageSync("address", address)
    }else {
      //3 诱导用户打开授权页面
      await openSetting()
      // 4 调用获取收货地址的 api 
      const address = await chooseAddress()
      wx.setStorageSync("address", address)
    }
    } catch (error) {
      console.log(error)
    }




  },
  handleChange: function (e) {
    // 先找到被修改的商品的id
    let goods_id = e.target.dataset.index
    let cart = this.data.cart
    // 找到这个商品在cart里面的索引,这是一个数组，只能这样改了
    let index = cart.findIndex(v => v.goods_id === goods_id)
    cart[index].checked = !cart[index].checked
    // 修改cart 里面的这个商品的数据
    // 修改本地cart里面的数据
    wx.setStorageSync("cart", cart);
      
    const allChecked = cart.length?cart.every(v => v.checked):false
    let totalPrice = 0
    let totalNumber = 0
    // 选中了才计算。。。。
    cart.forEach(v => {
    if (v.checked) {
      totalPrice += v.goods_price * v.num
      totalNumber += v.num
    }
    })
    this.setData({
      cart,
      allChecked,
      totalPrice,
      totalNumber
    })
  },

  allCheckedChange: function () {
    let cart = this.data.cart
    this.setData({
      allChecked: !this.data.allChecked
    })
    cart.forEach(v => v.checked = this.data.allChecked)
    wx.setStorageSync("cart", cart);
      
    const allChecked = cart.length?cart.every(v => v.checked):false
    let totalPrice = 0
    let totalNumber = 0
    // 选中了才计算。。。。
    cart.forEach(v => {
    if (v.checked) {
      totalPrice += v.goods_price * v.num
      totalNumber += v.num
    }
    })
    this.setData({
      cart,
      allChecked,
      totalPrice,
      totalNumber
    })
  },
  goodsNumEdit: function (e) {
    // 先获取要修改商品的 id 和操作数
    let goods_id = e.currentTarget.dataset.index
    let operate = e.currentTarget.dataset.operate
    // 在cart里面找这个商品
    let cart = this.data.cart
    var index = cart.findIndex(v => v.goods_id === goods_id)
    cart[index].num += operate
    if (cart[index].num < 2 && operate == -1) {
      wx.showModal({
        title: '注意',
        content: '确认删除该商品？',
        success: (res) => {
          if (res.confirm) {
            cart.splice(index, 1)
            wx.setStorageSync("cart", cart);
            const allChecked = cart.length?cart.every(v => v.checked):false
    let totalPrice = 0
    let totalNumber = 0
    // 选中了才计算。。。。
    cart.forEach(v => {
    if (v.checked) {
      totalPrice += v.goods_price * v.num
      totalNumber += v.num
    }
    })
    this.setData({
      cart,
      allChecked,
      totalPrice,
      totalNumber
    })
          } else if (res.cancel) {
          }
        }
      })
    }
    wx.setStorageSync("cart", cart);
    const allChecked = cart.length?cart.every(v => v.checked):false
    let totalPrice = 0
    let totalNumber = 0
    // 选中了才计算。。。。
    cart.forEach(v => {
    if (v.checked) {
      totalPrice += v.goods_price * v.num
      totalNumber += v.num
    }
    })
    this.setData({
      cart,
      allChecked,
      totalPrice,
      totalNumber
    })
  },
  // 支付按钮
  async handlePay () {
    // 1. 判断有没有收货地址
    const address = this.data.address
    const totalNumber = this.data.totalNumber
    if (!address.userName) {
      await showToast({title: "您还没有选择收货地址"})
      return
    }
    // 2. 判断用户有没有选择商品
    if(totalNumber === 0) {
      await showToast({title: "您还没有选购商品"})
      return
    }
    // 3. 跳转到支付页面
    wx.navigateTo({
      url: '/pages/pay/index'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  
})